package com.tanhua.dubbo.mongo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //上传小视频
    public void saveVideo(Video video) {
    mongoTemplate.save(video);

    }

    //查询所有
    public List<Video> findAll(Integer page, Integer pagesize) {

        Query query=new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize).limit(pagesize);

        List<Video> videos = mongoTemplate.find(query, Video.class);

        return videos;
    }

    //根据id列表查询
    public List<Video> findByIds(String[] ids,Integer page, Integer pagesize) {

        if ((page-1)*pagesize < ids.length){

            Criteria criteria = Criteria.where("id").in(ids);
            Query query=Query.query(criteria)
                    .with(Sort.by(Sort.Order.desc("created")))
                    .skip((page-1)*pagesize).limit(pagesize);

            return mongoTemplate.find(query, Video.class);

        }else {
            //redis中数据不足时，查询mongoDB
            //计算查询的页码，（查询的页码 - redis中的总页数）
            //redis中的总页数
            int totalPage = PageUtil.totalPage(ids.length, pagesize);
            page=page-totalPage;
            return findAll(page,pagesize);
        }

    }

   // 视频记录翻页
    public PageResult findVideoList(Integer page, Integer pagesize, Long userId) {

        Criteria criteria = Criteria.where("userId").is(userId);

        Query query=Query.query(criteria);

        long count = mongoTemplate.count(query, Video.class);

        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize)
                .limit(pagesize);

        List<Video> videos = mongoTemplate.find(query, Video.class);

        return new PageResult(page,pagesize,count,videos);

    }
}
